/*
 * $RCSfile: SqlFileAction.java,v $
 * $Revision: 1.1 $
 * $Date: 2014-07-20 $
 *
 * Copyright (C) 2008 Skin, Inc. All rights reserved.
 *
 * This software is the proprietary information of Skin, Inc.
 * Use is subject to license terms.
 */
package com.skin.webcat.action;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;

import com.skin.j2ee.action.BaseAction;
import com.skin.j2ee.annotation.UrlPattern;
import com.skin.j2ee.util.Response;
import com.skin.util.HtmlUtil;
import com.skin.util.Path;
import com.skin.webcat.database.Column;
import com.skin.webcat.database.Table;
import com.skin.webcat.database.dialect.Dialect;
import com.skin.webcat.database.dialect.MySQLDialect;
import com.skin.webcat.database.sql.parser.CreateParser;
import com.skin.webcat.util.Webcat;

/**
 * <p>Title: SqlFileAction</p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2006</p>
 * @author xuesong.net
 * @version 1.0
 */
public class SqlFileAction extends BaseAction {
    /**
     * @throws IOException
     * @throws ServletException
     */
    @UrlPattern("/webcat/sql/list.html")
    public void list() throws IOException, ServletException {
        String filePath = Path.getStrictPath(this.getParameter("path"));
        String templateConfig = this.getParameter("templateConfig");

        if(templateConfig != null) {
            templateConfig = templateConfig.trim();
        }

        File file = Webcat.getFile(this.servletContext, filePath);

        if(file != null) {
            String source = Webcat.getSource(file);
            Dialect dialect = new MySQLDialect();
            CreateParser sqlParser = new CreateParser(dialect);
            List<Table> tableList = sqlParser.parse(source);

            this.setAttribute("filePath", filePath);
            this.setAttribute("fileName", file.getName());
            this.setAttribute("tableList", tableList);
            this.setAttribute("templateConfig", templateConfig);
        }
        this.forward("/template/webcat/sql/tableList.jsp");
    }

    /**
     * @throws IOException
     * @throws ServletException
     */
    @UrlPattern("/webcat/sql/fileList.html")
    public void fileList() throws IOException, ServletException {
        String filePath = Path.getStrictPath(this.getTrimString("path"));
        File file = Webcat.getFile(this.servletContext, filePath);

        if(file != null && file.isDirectory()) {
            File[] files = file.listFiles();
            this.setAttribute("fileList", files);
            this.setAttribute("filePath", filePath);
            this.setAttribute("fileName", file.getName());
        }
        this.forward("/template/webcat/sql/fileList.jsp");
    }

    /**
     * @throws IOException
     */
    @UrlPattern("/webcat/sql/getTableXml.html")
    public void getTableXml() throws IOException {
        String contextPapth = this.getContextPath();
        String filePath = Path.getStrictPath(this.getParameter("path"));
        StringBuilder buffer = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<tree>");

        if(filePath != null) {
            String source = Webcat.getSource(this.servletContext, filePath);
            Dialect dialect = new MySQLDialect();
            CreateParser sqlParser = new CreateParser(dialect);
            List<Table> tableList = sqlParser.parse(source);

            if(tableList != null && tableList.size() > 0) {
                for(Table table : tableList) {
                    buffer.append("<treeNode");
                    buffer.append(" title=\"");
                    buffer.append(HtmlUtil.encode(table.getTableName()));
                    buffer.append("\"");
                    buffer.append(" href=\"");
                    buffer.append(contextPapth);
                    buffer.append("/webcat/sql/edit.html?path=");
                    buffer.append(HtmlUtil.encode(filePath));
                    buffer.append("&amp;tableName=");
                    buffer.append(HtmlUtil.encode(table.getTableName()));
                    buffer.append("\"/>");
                }
            }
        }
        buffer.append("</tree>");
        this.response.setHeader("Cache-Control", "no-cache");
        this.response.setHeader("Pragma", "no-cache");
        this.response.setHeader("Expires", "0");
        Response.write(this.request, this.response, "text/xml; charset=UTF-8", buffer.toString());
    }

    /**
     * @throws IOException
     * @throws ServletException
     */
    @UrlPattern("/webcat/sql/edit.html")
    public void edit() throws IOException, ServletException {
        this.edit("/template/webcat/sql/tableEdit.jsp");
    }

    /**
     * @throws IOException
     * @throws ServletException
     */
    @UrlPattern("/webcat/sql/generate.html")
    public void generate() throws IOException, ServletException {
        this.edit("/template/generate/tableEdit.jsp");
    }

    /**
     * @param page
     * @throws IOException
     * @throws ServletException
     */
    public void edit(String page) throws IOException, ServletException {
        String tableName = this.getParameter("tableName");
        String filePath = Path.getStrictPath(this.getParameter("path"));

        if(filePath != null) {
            String source = Webcat.getSource(this.servletContext, filePath);
            Dialect dialect = new MySQLDialect();
            CreateParser sqlParser = new CreateParser(dialect);
            List<Table> tableList = sqlParser.parse(source);
            Map<String, Table> tableMap = this.getTableMap(tableList);
            Table table = tableMap.get(tableName);
            List<Column> columns = table.getColumns();

            if(columns != null) {
                for(Column column : columns) {
                    column.setTable(null);
                }
            }

            this.setAttribute("table", table);
            this.setAttribute("columns", columns);
            this.setAttribute("tableName", tableName);
            this.setAttribute("filePath", filePath);
            this.setAttribute("author", System.getProperty("user.name"));
        }
        this.forward(page);
    }

    /**
     * @throws IOException
     * @throws ServletException
     */
    @UrlPattern("/webcat/sql/insert.html")
    public void insert() throws IOException, ServletException {
        String tableName = this.getParameter("tableName");
        String filePath = Path.getStrictPath(this.getParameter("path"));

        if(filePath != null) {
            String source = Webcat.getSource(this.servletContext, filePath);
            Dialect dialect = new MySQLDialect();
            CreateParser sqlParser = new CreateParser(dialect);
            List<Table> tableList = sqlParser.parse(source);
            Map<String, Table> tableMap = this.getTableMap(tableList);
            Table table = tableMap.get(tableName);
            List<Column> columns = table.getColumns();

            if(columns != null) {
                for(Column column : columns) {
                    column.setTable(null);
                }
            }

            this.setAttribute("table", table);
            this.setAttribute("columns", columns);
            this.setAttribute("tableName", tableName);
            this.setAttribute("filePath", filePath);
        }
        this.forward("/template/webcat/insertEdit.jsp");
    }

    /**
     * @param tableList
     * @return Map<String, Table>
     */
    public Map<String, Table> getTableMap(List<Table> tableList) {
        Map<String, Table> map = new HashMap<String, Table>();

        if(tableList != null && tableList.size() > 0) {
            for(Table table : tableList) {
                map.put(table.getTableName(), table);
            }
        }
        return map;
    }
}
